#include "controlDevice.h"
#include "msg_queue.h"
#include <time.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>

/*

struct controlDevice
{
    char name[128]; // 设备名称
    int pin;  // 设别引脚
    int pinStatus; // 引脚状态
    int pinMode; // 引脚模式
    int (*deviceInit)(); // 初始化函数
    int (*open)(); // 打开函数
    int (*close)(); // 关闭函数
    int (*clearConfig)(); // 清除内存

    struct controlDevice *Next;
};


 */


int fireClear(void);

int fireInit(void);

int fireStatusRead(void);

void *smoke_get(void* arg);


struct controlDevice fire = {
    .name       = "fire",
    .pin        = 25,
    .pinStatus  = HIGH,
    .pinMode    = INPUT,
    .deviceInit = fireInit,
    .clearConfig= fireClear,
    .readStatus = fireStatusRead,
    .get        = smoke_get
};

int fireStatusRead(void)
{
    fire.pinStatus = digitalRead(fire.pin);
    return fire.pinStatus;
}



int fireClear(void)
{
    
}


int fireInit(void)
{
    pinMode(fire.pin,fire.pinMode);
    digitalWrite(fire.pin,fire.pinStatus);
    return 1;
}

void *smoke_get(void* arg)
{
    mqd_t mqd = -1;
    int smoke_signal = 0; // 烟雾信号
    int status = fire.pinStatus;
    int sendsize = -1;
    char buffer[10] = {0x09,0x08,0x06,0x00,0x08,0x09};

    pthread_detach(pthread_self());// 分离线程
    printf("%s 线程启动\n", __func__);
    if(arg != NULL)
    {
        mqd = (mqd_t)*((char *)arg);
    }
    if ((mqd_t)-1 == mqd)
    {
        printf("mqd获取失败\n");
        pthread_exit(0);
    }
    while(1)
    {
        status = digitalRead(fire.pin);
        // memset(buffer,'\0',sizeof(buffer));
        if(status == LOW && smoke_signal == 0)
        {
            smoke_signal = 1;
            buffer[3] = 0x01;
            sendsize = send_message(mqd,buffer,sizeof(buffer)); // 打开喇叭
            printf("数据发送成功：%d|%d\r\n",buffer[2],buffer[3]);
            if(sendsize == -1)
            {
                continue;
            }
        }
        else if(status == HIGH && smoke_signal == 1)
        {
            smoke_signal = 0;
            buffer[3] = 0x00;
            sendsize = send_message(mqd,buffer,sizeof(buffer));
            printf("数据发送成功：%d|%d\r\n",buffer[2],buffer[3]);
            if(sendsize == -1)
            {
                continue;
            }
        }
        sleep(5);
    }
    pthread_exit(0);
}

struct controlDevice* addFireToDeviceLink(struct controlDevice* phead)
{
    if(phead == NULL)
    {
        return &fire;
    }
    else
    {
        fire.Next = phead;
        phead = &fire;
        return phead;
    }

}

